package com.wavecoler.professor.servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.google.gson.Gson;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.wavecoler.professor.objects.Course;
import com.wavecoler.professor.objects.User;
import com.wavecoler.utilities.Utilities;

@SuppressWarnings("serial")
public class AuthenticateServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		ArrayList<Course> courses = new ArrayList<Course>();
		String username = req.getParameter("user[login]");
		String password = req.getParameter("user[password]");
		System.out.println(username);
		System.out.println("Entro...");
		System.out.println(password);
		
		
		String passEncriptada = Utilities.toMd5(password);
		System.out.println(passEncriptada);
		String cut = passEncriptada.substring(0, 8);
		
		Client service = Client.create();
		service.setConnectTimeout(10000);
		WebResource webResource = service.resource("http://wavecoler.lag.itesm.mx:8080/WaveColerWebServices/rest/users/user/"+username+"/");
			ClientResponse respuesta = webResource.accept("application/json").get(ClientResponse.class);
       // if (respuesta.getStatus() == 200) {
        	JSONObject jsonOb = new JSONObject();
		    jsonOb = respuesta.getEntity(JSONObject.class);	
		
		    Gson gson = new Gson();
		    BufferedReader br = new BufferedReader(new StringReader(jsonOb.toString()));
		    User usuario = gson.fromJson(jsonOb.toString(), User.class);
		
			try {
				if(usuario.getUserType().equals("Professor")){
			//Aqui obtenemos los cursos que vamos a cargar...
			Client anotherService = Client.create();
			WebResource webResourcetwo = anotherService.resource("http://wavecoler.lag.itesm.mx:8080/WaveColerWebServices/rest/courses/professor/"+jsonOb.getString("userId")+"/");
			ClientResponse respuestados = webResourcetwo.accept("application/json").get(ClientResponse.class);
			final JSONObject jsonObjecti = respuestados.getEntity(JSONObject.class);	
			JSONArray ble = jsonObjecti.getJSONArray("course");
			
			for(int i = 0; i < ble.length(); i++){
				JSONObject bli = ble.getJSONObject(i);
				Gson gsons = new Gson();
				BufferedReader brs = new BufferedReader(new StringReader(bli.toString()));
				Course curso = gsons.fromJson(bli.toString(), Course.class);
				courses.add(curso);
			}
			
		}else if(usuario.getUserType().equals("Student")){
			Client anotherService = Client.create();
			WebResource webResourcetwo = anotherService.resource("http://wavecoler.lag.itesm.mx:8080/WaveColerWebServices/rest/courses/student/"+jsonOb.getString("userId")+"/");
			ClientResponse respuestados = webResourcetwo.accept("application/json").get(ClientResponse.class);
			final JSONObject jsonObjecti = respuestados.getEntity(JSONObject.class);	
			try{
			JSONArray ble = jsonObjecti.getJSONArray("course");
			for(int i = 0; i < ble.length(); i++){
				JSONObject bli = ble.getJSONObject(i);
				Gson gsons = new Gson();
				BufferedReader brs = new BufferedReader(new StringReader(bli.toString()));
				Course curso = gsons.fromJson(bli.toString(), Course.class);
				courses.add(curso);
			}
			}catch (Exception e){
				courses.clear();
				JSONObject bli = jsonObjecti.getJSONObject("course");
				Gson gsons = new Gson();
				BufferedReader brs = new BufferedReader(new StringReader(bli.toString()));
				Course curso = gsons.fromJson(bli.toString(), Course.class);
				courses.add(curso);
			}
			
				}
				
			String contraReal = null;
			contraReal = usuario.getPassword();
			boolean activo = jsonOb.getBoolean("active");
			System.out.println("Contraseña real: " + contraReal);
			System.out.println("compare: " + contraReal + " y " + cut);
			System.out.println("Lenght: " + contraReal.length() +" "+ cut.length());
			if(cut.equals(contraReal) && activo == true && usuario.getUserType().equals("Professor") ){
				System.out.println("Entre...");
				HttpSession session = req.getSession();
				session.setAttribute("username",username);
				session.setAttribute("name", usuario.getFirstName());
				session.setAttribute("cursos",courses);
				String address = "jsps/indexprofessor.jsp";
			    RequestDispatcher dispatcher = req.getRequestDispatcher(address);
			    dispatcher.forward(req, resp);		
			}else if(cut.equals(contraReal) && activo == true && usuario.getUserType().equals("Student")){
				System.out.println("Entre...");
				HttpSession session = req.getSession();
				session.setAttribute("username",username);
				session.setAttribute("name", usuario.getFirstName());
				session.setAttribute("cursos",courses);
				String address = "jsps/indexalumno.jsp";
			    RequestDispatcher dispatcher = req.getRequestDispatcher(address);
			    dispatcher.forward(req, resp);
			}else{
				System.out.println("No Entre...");
				String address = "jsps/login.jsp";
			    RequestDispatcher dispatcher = req.getRequestDispatcher(address);
			    dispatcher.forward(req, resp);	
			}
				
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		//Comprobar igualdad de contraseña, poner username en session y abrir nueva pagina.	
       // }
        }

}

